package com.atom.module.mvvm.base.view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.atom.module.mvvm.BR
import com.atom.module.mvvm.base.ApiViewModel

class MVVMDialog<Binding : ViewDataBinding, ViewModel : ApiViewModel>(
    private val content: Context,
    private val layout: Int,
    private val viewModel: ViewModel,
    private val id: Int = BR._all,
) :
    LifecycleOwner,
    LifecycleEventObserver {

    override val lifecycle by lazy { LifecycleRegistry(this) }

    private lateinit var binding: Binding

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        lifecycle.handleLifecycleEvent(event)
    }

    fun show(block: (binding: Binding, dialogViewModel: ViewModel) -> Unit): View {
        this.binding = DataBindingUtil.inflate(
            LayoutInflater.from(content),
            layout,
            null,
            false
        )
        this.binding.lifecycleOwner = this
        this.viewModel.setLifecycleOwner(this)
        this.binding.setVariable(id, viewModel)
        block.invoke(this.binding, this.viewModel)
        return this.binding.root
    }
}